import React from "react"
import { withRouter } from "react-router-dom"

function Login(props) {
  let elements = {}
  const [loginMsg, setLoginMsg] = React.useState(false)

  const handleLoginClick = (e) => {
    e.preventDefault()
    fetch(props.loginUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: analyzeForm(),
    })
      .then((res) => res.text())
      .then((json) => {
        return JSON.parse(json)
      })
      .then((loginResponse) => {
        setLoginMsg(loginResponse.message)
        props.setStudentId(loginResponse.studentId)
        if (loginResponse.success) {
          console.log(props.history)
          props.history.push("/course")
        }
      })
  }

  const analyzeForm = () => {
    let username = elements.username.value
    let password = elements.password.value
    let isTeacher = elements.teacher.checked
    let obj = {
      username,
      password,
      identity: isTeacher ? "teacher" : "student",
    }
    console.log(obj)
    return JSON.stringify(obj)
  }

  return (
    <>
      <form action={props.loginUrl} method="post">
        <input
          type="radio"
          name="identity"
          value="teacher"
          id="identity-teacher"
          ref={(e) => (elements.teacher = e)}
        />
        <label htmlFor="identity-teacher">我是老师</label>

        <input
          type="radio"
          name="identity"
          value="student"
          id="identity-student"
          ref={(e) => (elements.student = e)}
        />
        <label htmlFor="identity-student">我是学生</label>

        <br />
        <label htmlFor="username">用户名：</label>
        <input
          type="text"
          name="username"
          id="username"
          autoComplete="off"
          ref={(e) => (elements.username = e)}
        />

        <br />
        <label htmlFor="password">密码：</label>
        <input
          type="password"
          name="password"
          id="password"
          autoComplete="off"
          ref={(e) => (elements.password = e)}
        />

        <br />
        <input
          type="submit"
          value="登录"
          id="login-submit"
          onClick={handleLoginClick}
        />
      </form>
      <p id="login-msg">{loginMsg ? loginMsg : ""}</p>
      <button
        onClick={() => {
          props.history.push("/register")
        }}
      >
        尚无账号，现在注册
      </button>
    </>
  )
}

export default withRouter(Login)
